package me.wz.util.sdbc.dialect;

import me.wz.util.sdbc.IDialect;
import me.wz.util.sdbc.Page;
import me.wz.util.sdbc.Pagination;

import java.util.Map;

public class Oracle extends Mysql {

    private static final String rn = ("rn_" + System.currentTimeMillis()).toUpperCase();

    @Override
    public String query(String select, Pagination pagination) {
        int offset = Math.max(0, pagination.getPageNum() - 1) * Math.abs(pagination.getPageSize()) + 1;
        int limit = offset + Math.abs(pagination.getPageSize()) + (pagination.getHasMoreMode() ? 1 : 0);
        String orderBy = (isBlank(pagination.getOrderBy()) ? "" : "order by " + pagination.getOrderBy());
        return "select * from (select a.*, rownum as " + rn + " from (" + select + ")a " + orderBy + " where " + rn + " < " + limit + ") where " + rn + " >= " + offset;
    }

    @Override
    public <T>Page<T> revert(Page<T> page) {
        for(T item : page.getItems()) {
            if( !Map.class.isInstance(item) ) {
                break;
            }
            ((Map<?, ?>)item).remove(rn);
        }
        return page;
    }
}
